import storage, {load} from '@/config/storage';
import {Effect, Model, SubscriptionsMapObject} from 'dva-core-ts';
import {Reducer} from 'redux';
import {GetCategoryData} from './../api/category';
import {RootState} from '@/models/index';

export interface ICategory {
  id: string;
  name: string;
  classify?: string;
}

interface CategoryModelState {
  myCategorys: ICategory[];
  categorys: ICategory[];
  isEdit: boolean;
}

interface CategoryModel extends Model {
  namespace: 'category';
  state: CategoryModelState;
  effects: {
    loadData: Effect;
    toggle: Effect;
  };
  reducers: {
    setState: Reducer<CategoryModelState>;
  };
  subscriptions: SubscriptionsMapObject;
}

const initialState = {
  myCategorys: [
    {
      id: 'home',
      name: '推荐',
    },
    {
      id: 'vip',
      name: 'vip',
    },
  ],
  categorys: [],
  isEdit: false,
};

const categoryModel: CategoryModel = {
  namespace: 'category',
  state: initialState,
  reducers: {
    setState(state, {payload}) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  effects: {
    *loadData(_, {call, put}) {
      const myCategorys = yield call(load, {key: 'myCategorys'});
      const categorys = yield call(load, {key: 'categorys'});
      yield put({
        type: 'setState',
        payload: myCategorys ? {myCategorys, categorys} : {categorys},
      });
    },
    *toggle({payload}, {put, select}) {
      let category = yield select(({category}: RootState) => category);
      console.log('myCategorys', payload.myCategorys);
      if (payload.myCategorys) {
        yield put({
          type: 'setState',
          payload: {
            isEdit: !category.isEdit,
            myCategorys: payload.myCategorys,
          },
        });
        if (category.isEdit) {
          storage.save({
            key: 'myCategorys',
            data: payload.myCategorys,
          });
        }
      } else {
        yield put({
          type: 'setState',
          payload: {
            isEdit: !category.isEdit,
          },
        });
      }
    },
  },
  subscriptions: {
    setup({dispatch}) {
      dispatch({type: 'loadData'});
    },
    asyncStorage() {
      storage.sync.categorys = async () => {
        let res = await GetCategoryData();
        return res.data;
      };
      storage.sync.myCategorys = async () => {
        return null;
      };
    },
  },
};

export default categoryModel;
